package com.lhczf.net;

import com.lhczf.App;
import com.lhczf.config.ProxyBean;
import com.lhczf.config.ProxyYmlConfig;
import com.lhczf.proxy.ProxyRuntime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.StandardSocketOptions;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.ThreadFactory;

public class AIOBind {
    private static final Logger LOGGER = LoggerFactory.getLogger(AIOBind.class);

    public static void beginToBindAddr(String ip, int port) {
        int processorCount = Runtime.getRuntime().availableProcessors();
        AsynchronousChannelGroup channelGroup;
        AsynchronousServerSocketChannel serverSocketChannel = null;


        InetSocketAddress inetSocketAddress = new InetSocketAddress(ip, port);

        try {
            channelGroup = AsynchronousChannelGroup.withFixedThreadPool(processorCount,
                    new ThreadFactory() {
                        private int inx = 1;

                        @Override
                        public Thread newThread(Runnable r) {
                            Thread th = new Thread(r);
                            th.setName("$AIO" + (inx++));
                            LOGGER.info("created new AIO thread " + th.getName());
                            return th;
                        }
                    });
            serverSocketChannel = AsynchronousServerSocketChannel.open(channelGroup);
            serverSocketChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
            serverSocketChannel.setOption(StandardSocketOptions.SO_RCVBUF, 16 * 1024);

            serverSocketChannel.bind(inetSocketAddress, 100);
        } catch (IOException e) {
            e.printStackTrace();
        }
        AIOServerHandler aioCompletionHandler = new AIOServerHandler(serverSocketChannel);
        serverSocketChannel.accept(null, aioCompletionHandler);
    }
}
